<?php

namespace app\money\controller;

use app\admin\common\Base;
use think\Db;
use app\admin\common\Excel;
//其它支出单
class Oriexp extends Base
{
    public function index()
    {

        $data = $this->request->param();

        $this->assign('o_type',14);//高级搜索状态（14：其他支出单记录）

        if (isset($data['ajax']) && $data['ajax'] == 100) {
            $map = '';
            $page = isset($data['page']) ? $data['page'] : 1;
            $page = intval($page);
            $limit = isset($data['rows']) ? $data['rows'] : 10;
            $limit = intval($limit);
            $start = $limit * ($page - 1);

            //搜索
            if (isset($data['search'])) {

                if ($data['search'] == 0) {

                    $field = 'sn|mark';
                    $sonField = 'name';
                    $keywork = $data['matchCon'];
                    $value = ['customer','user_id'];
                    $where = getSearch($field, $sonField, $keywork, $value);

                    $time1 = strtotime($data['datew']);
                    $time2 = strtotime($data['dateo']);

                    $sql = Db::name('income')->where('type', 1)->where('is_del', 0)->where('enterprise_id', $this->EnterpriseId)->where($where);
                    $sql = !isset($time1) && !isset($time2) ? $sql :$sql->whereTime('dj_time','between',[$time1,$time2]);
                    $list = $sql->order('id desc')->limit($start, $limit)->select();
                    $count = sizeof($list);

                //高级搜索
                }else{

                    $stime = [$data['fromDate'],$data['toDate']];
                    $tables = ['user_id','add_user','last_user','shenhe_user','status'];
                    $keywork = [$data['supplier_id'],$data['usersCreatId'],$data['usersModifyId'],$data['usersChecksId'],$data['checkStatusId']];
                    //查询方法    
                    $sql = Db::name('income')->where('is_del', 0)->where('type', 1)->where('enterprise_id',$this->EnterpriseId);
                    //模糊查询
                    $sql = empty($data['remarkCon']) ? $sql : $sql->where('mark','like','%'.$data['remarkCon'].'%');
                    //获取时间值 用于判断
                    $sql = empty($stime[0]) && empty($stime[1]) ? $sql : $sql->whereTime('dj_time','between',$stime);
                    //精确查询
                    for ($j=0; $j <count($keywork) ; $j++) {
                        $sql = $keywork[$j] == '' ? $sql : $sql->where($tables[$j],$keywork[$j]);
                    } 
                        $list = $sql->order('id desc')->limit($start, $limit)->select();
                        // halt($list)
                        $count = sizeof($list);
                }

            }else{

                if ($map == '') {
                $list = Db::name('income')->where('type', 1)->where('is_del', 0)->where('enterprise_id', $this->EnterpriseId)->order('id desc')->limit($start, $limit)->select();
                $count = Db::name('income')->where('type', 1)->where('enterprise_id', $this->EnterpriseId)->where('is_del', 0)->count();
                } else {
                    $list = Db::name('income')->where('type', 1)->where('is_del', 0)->where('enterprise_id', $this->EnterpriseId)->order('id desc')->limit($start, $limit)->select();
                    $count = Db::name('income')->where('type', 1)->where('enterprise_id', $this->EnterpriseId)->where('is_del', 0)->count();
                }

            }
            foreach ($list as $key => &$val) {
                //$val['zt']=$val['status'];//行高
                // halt($val);
                $val['dj_time'] = date('Y-m-d', $val['dj_time']);
                $c = Db::name('customer')->where('id', $val['user_id'])->find();
                $val['customer_name'] = $c['sn'] . ' ' . $c['name'];
                $val['add_user_name'] = $val['add_user'] == 0 ? '' : Db::name('auth_user')->where('id', $val['add_user'])->value('name');
                $val['shenhe_user_name'] = $val['shenhe_user'] == 0 ? '' : Db::name('auth_user')->where('id', $val['shenhe_user'])->value('name');
                if ($val['jine'] == $val['now_jine']) {
                    $val['sk_status'] =  "全部付款";
                } else {
                    if (intval($val['now_jine']) == 0) {
                        $val['sk_status'] = "未付款";
                    } else {
                        $val['sk_status'] = "部分付款";
                    }
                }
            }    

                // halt($list);
                return $this->grid_data($list, $count, $page, $limit);
            
        }
        $today = date('Y-m-d', time());
        $mon_start = date('Y-m', time()) . '-01';
        $this->assign('today', $today);
        $this->assign('mon_start', $mon_start);
        return $this->fetch();
    }


    public function add()
    {
        $sn = osn('QTZC', 6);
        //支出类别
        $income_type = Db::name('money_type')->where('is_del', 0)->where('enterprise_id', $this->EnterpriseId)->order('id asc')->select();
        $today = date('Y-m-d', time());
        $this->assign('today', $today);
        $this->assign('sn', $sn);
        $this->assign('income_type', $income_type);
        return $this->fetch();
    }


    // 添加-更新
    public function save()
    {
        $status = 0;
        $msg = "操作失败";
        $data = $this->request->param();

        // halt($data);
        Db::startTrans(); // 启动事务
        $data['type'] = 1; //0其它收入单；1其它支出单
        $res = $this->inset_income($data);
        if ($res == 1) {
            Db::commit(); // 提交事务
            $status = 1;
            $msg = "添加成功";
        } else if ($res == 2) {
            Db::rollback(); // 回滚事务
            $msg = "存在相同的单据号";
        } else {
            Db::rollback(); // 回滚事务
        }
        return ['status' => $status, 'msg' => $msg];
    }



    //审核与反审核
    public function shenhe()
    {
        $data = $this->request->param();
        $status = 0;
        // intval(0);
        // exit();
        $msg = "操作失败";
        $id = $data['id'];
        $type = $data['type'];
        Db::startTrans(); // 启动事务
        $info = Db::name('income')->where('id', $id)->where('is_del', 0)->where('enterprise_id', $this->EnterpriseId)->find();
        //halt( $info);
        //if($info['xht_id']==0&&$info['xh_id']==0){
        if ($type == 1) {
            if ($info['status'] == 1) {
                $msg = "已审核过，不可审核";
            } else {
                $update = [
                    'status' => 1,
                    'updatetime' => time(),
                    'shenhe_time' => time(),
                    'shenhe_user' => $this->Userinfo['id'],
                    'last_user' => $this->Userinfo['id'],
                ];
                $result = Db::name('income')->where('id', $id)->where('is_del', 0)->where('enterprise_id', $this->EnterpriseId)->update($update);
                if ($result) {

                    //添加客户资金流水
                    $user_money['system_price'] = $info['jine']; //应收金额-优惠后的价格
                    $user_money['user_price'] = $info['now_jine']; //实收金额-本次预收款
                    $user_money['user_id'] = $info['user_id']; //客户ID
                    $user_money['type'] = 1; //0客户付款；1客户进款
                    $user_money['o_way'] = 8; // 0,销售单；1.销售退货单；2，采购单；3采购退货单；4收款单；5付款单;6,期初金额7，其它收入单；8其它支出单
                    $user_money['psn'] = $info['sn'];
                    $user_money['pid'] = $info['id'];
                    $user_money['enterprise_id'] = $this->EnterpriseId;
                    $res1 = add_user_money($user_money);

                    if ($res1 == 0) {
                        $msg = "参数错误";
                    }
                    if ($res1 == 1) {
                        $status = 1;
                        $msg = "操作成功";
                    }
                }
            }
        }
        if ($type == 2) {
            if ($info['status'] == 0) {
                $msg = "已审核过，不可审核";
            } else {
                $update = [
                    'status' => 0,
                    'updatetime' => time(),
                    'shenhe_time' => 0,
                    'shenhe_user' => 0,
                    'last_user' => $this->Userinfo['id'],
                ];
                $result = Db::name('income')->where('id', $id)->where('is_del', 0)->where('enterprise_id', $this->EnterpriseId)->update($update);
                if ($result) {
                    $upda = [
                        'is_del' => 1,
                        'updatetime' => time(),
                        'last_user' => $this->Userinfo['id'],
                    ];
                    $re = Db::name('user_money')->where('pid', $info['id'])->where('psn', $info['sn'])->where('is_del', 0)->find();
                    if ($re) {
                        unset($upda['last_user']);
                        //删除客户资金流水
                        $resu1 = del_user_money($upda, $info);
                        if ($resu1 == 1) {
                            $status = 1;
                            $msg = "操作成功";
                        } else {
                            $status = 0;
                            $msg = "操作失败";
                        }
                    }
                }
            }
        }
        // }else {
        //     $msg="存在关联单据不能操作";
        // }
        if ($status == 1) {
            Db::commit(); // 提交事务
        } else {
            Db::rollback(); // 回滚事务
        }
        return ['status' => $status, 'msg' => $msg];
    }

    // //删除
    public function del($id)
    {
        $status = 0;
        $msg = "删除失败";
        // 启动事务
        Db::startTrans();
        $info = Db::name('income')->where('id', $id)->where('is_del', 0)->where('enterprise_id', $this->EnterpriseId)->find();
        // halt( $info);
        if ($info['status'] != 1) {
            $update = [
                'is_del' => 1,
                'updatetime' => time(),
                'last_user' => $this->Userinfo['id'],
            ];
            $result = Db::name('income')->where('id', $id)->where('is_del', 0)->where('enterprise_id', $this->EnterpriseId)->update($update);
            if ($result) {
                $c = Db::name('income_good')->where('pid', $id)->where('is_del', 0)->where('enterprise_id', $this->EnterpriseId)->select();
                if (!empty($c)) {
                    $res = Db::name('income_good')->where('pid', $id)->where('is_del', 0)->where('enterprise_id', $this->EnterpriseId)->setField('is_del', 1);
                    if ($res) {
                        Db::commit(); // 提交事务
                        $status = 1;
                        $msg = "删除成功";
                    }
                } else {
                    Db::commit(); // 提交事务
                    $status = 1;
                    $msg = "删除成功";
                }
            }
        } else {
            // $msg="存在关联单据不能删除";
            $msg = "已审核单据不能删除";
        }
        if ($status != 1) {
            // 回滚事务
            Db::rollback();
        }
        return ['status' => $status, 'msg' => $msg];
    }

    //订单详情
    public function details()
    {
        $data = $this->request->param();
        $oid = $data['order_id'];
        $o = Db::name('income')->where('id', $oid)->where('is_del', 0)->find();
        $customer = Db::name('customer')->where('id', $o['user_id'])->find();
        $o['customer_name'] = $customer['sn'] . ' ' . $customer['name'];

        //halt($o);
        if (isset($data['ajax']) && $data['ajax'] == 100) {
            $map = '';
            $page = isset($data['page']) ? $data['page'] : 1;
            $page = intval($page);
            $limit = isset($data['rows']) ? $data['rows'] : 10;
            $limit = intval($limit);
            $start = $limit * ($page - 1);

            //halt($o);
            if ($map == '') {
                $list = Db::name('income_good')->where('pid', $o['id'])->where('is_del', 0)->order('addtime desc,id asc')->limit($start, $limit)->select();
                $count = Db::name('income_good')->where('pid', $o['id'])->where('is_del', 0)->count();
            } else {
                $list = Db::name('income_good')->where('pid', $o['id'])->where('is_del', 0)->order('sort desc,id asc')->limit($start, $limit)->select();
                $count = Db::name('income_good')->where('pid', $o['id'])->where('is_del', 0)->count();
            }

            foreach ($list as $key => &$val) {
                $val['income_type_name'] = Db::name('money_type')->where('id', $val['income_type_id'])->value('name'); //收入类别名称
                $val['jine'] = $val['price'];
            }
            //halt($o);
            //少于5条则填充
            if (5 - $count > 0) {
                for ($i = 0; $i < 5 - $count; $i++) {
                    array_push($list, []);
                }
            }

            return $this->grid_data($list, $count, $page, $limit);
        }
        //支出类别
        $income_type = Db::name('money_type')->where('is_del', 0)->where('enterprise_id', $this->EnterpriseId)->order('id asc')->select();
        $this->assign('income_type', $income_type);

        $this->assign('info', $o);
        return $this->fetch();
    }
    //导出
    public function export(){
        $data = $this->request->param();

        $rowid = explode(" ",$data['rowid']);
        $title = [
            'dj_time' => '单据日期',
            'sn' => '单据编号',
            'user_id'=>'供应商',
            'settle_type_id'=>'结束方式',
            'jine' => '整单金额',
            'qk_jine'=>'本次欠款',
            'now_jine' => '已付金额',
            'add_user'=>'制单人',
            'shenhe_user' => '审核人',
            'sk_status' => '付款状态',
            'mark' => '备注',
            'income_type_id'=>'支出类别',
            'price' => '金额',
            'good_mark' => '结算号'
        ]; 
        
        $arr_list = [];
        $list = Db::name('income')->where('type', 1)->where('id','in',$rowid)->where('is_del', 0)->where('enterprise_id', $this->EnterpriseId)->order('id desc')->select();
        $jine = Db::name('income')->where('type', 1)->where('id','in',$rowid)->where('is_del', 0)->where('enterprise_id', $this->EnterpriseId)->order('id desc')->sum('jine');
        $now_jine = Db::name('income')->where('type', 1)->where('id','in',$rowid)->where('is_del', 0)->where('enterprise_id', $this->EnterpriseId)->order('id desc')->sum('now_jine');
        $qk_jine = Db::name('income')->where('type', 1)->where('id','in',$rowid)->where('is_del', 0)->where('enterprise_id', $this->EnterpriseId)->order('id desc')->sum('qk_jine');
        // halt($list);
        $zh = [
            'dj_time' => '合计',
            'sn' => null,
            'user_id'=>'',
            'settle_type_id'=>'',
            'jine' => $jine,
            'qk_jine'=>$qk_jine,
            'now_jine'=>$now_jine,
            'add_user'=>'',
            'shenhe_user' => '',
            'sk_status' => '',
            'mark' => '',
            'income_type_id'=>'',
            'price' => '',
            'good_mark' => ''
        ];
        foreach ($list as $k=>$v) {
            $v['dj_time'] = date('Y-m-d', $v['dj_time']);
            $v['user_id'] = Db::name('customer')->where('id', $v['user_id'])->value('name');
            $type = db('income_good')->where('pid',$v['id'])->select();
            $hj = db('income_good')->where('pid',$v['id'])->sum('price');
             // halt($type);
            $v['settle_type_id']='现金';
            if ($v['jine'] == $v['now_jine']) {
                    $v['sk_status'] =  "全部付款";
                } else {
                    if (intval($v['now_jine']) == 0) {
                        $v['sk_status'] = "未付款";
                    } else {
                        $v['sk_status'] = "部分付款";
                    }
                }
            foreach ($type as $key=>$value) {
                $v['income_type_id'] = db('money_type')->where('id',$value['income_type_id'])->value('name');
                $v['price'] = $value['price'];
                $v['good_mark'] = $value['mark'];
                array_push($arr_list,$v);
            }
            // halt($a);
            $k = [
                'dj_time' => '',
                'sn' => $v['sn'],
                'user_id'=>'',
                'settle_type_id'=>'',
                'jine' => '',
                'now_jine'=>'',
                'qk_jine'=>'',
                '$now_jine'=>'',
                'add_user'=>'',
                'shenhe_user' => '',
                'sk_status' => '',
                'mark' => '',
                'income_type_id'=>'合计',
                'price' => $hj,
                'good_mark' => ''
            ];
            array_push($arr_list,$k);
        }
        array_push($arr_list,$zh);
        // halt($arr_list);
        // array_multisort($distance, SORT_DESC, $arr_list);//按照ID大小排序
        //添加标题到数组头部
        array_unshift($arr_list,$title);
        $kong_arr=$title;
        foreach ($kong_arr as $ke1 => $va1) {
            $kong_arr[$ke1]='';
        }
        for ($i=0; $i <3 ; $i++) { 
            array_unshift($arr_list,$kong_arr);
        }
         //根据此参数获取数据中的值，要与表格标题键名对应
        $keys=[];
        foreach ($title as $k2 => $v2) {
            array_push($keys, $k2);
        }
        $merge=[];
        $options=[];
        $o_type=-1;
        $merge=[//合并
                    'start'=>5,
                    'arr_zimu'=>['A','B','C','D','E','F','G','H','I','J'],
                    'keyword'=>'sn',
                ];
        $options=[
            'alignCenter'=>['A','B','C','D','E','F','G','H','I','J','K','L','M','N'],//居中
            'bold'=>['A1:N3','A4:N4'],//加粗
            'fontSize'=>['zimu'=>['A1'],'size'=>20],//字体大小
        ];
        $title=[//标题
            'title'=>"其他支出单",
            'max_zimu'=>"N",
            'number'=>'3',
        ];
        $excel_export_title="其他支出单_" . date('Y-m-d_His') . '.xlsx';//文件名称
        $excel = new Excel();
        $excel->exportExcel($arr_list,$keys,$excel_export_title,$options,$o_type,$merge,$title);
        
        exit();
    }
    
}
